package middleware

import (
	"api/internal/types"
	"api/pkg"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AuthtemplateMiddleware struct {
}

func NewAuthtemplateMiddleware() *AuthtemplateMiddleware {
	return &AuthtemplateMiddleware{}
}

func (m *AuthtemplateMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			response := types.Response{
				Code: 500,
				Msg:  "未登录",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return

		}
		getToken, s := pkg.GetToken(token)
		if s != "" {
			response := types.Response{
				Code: 500,
				Msg:  s,
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return

		}
		r.ParseForm()
		r.Form.Set("userId", getToken["userId"].(string))

		// Passthrough to next handler if need
		next(w, r)
	}
}
